﻿using MQTTnet;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using MQTTnet.Protocol;
using MQTTnet.Server;
using SharpPcap;
using System;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IoTClient.Tool.Controls
{
    public partial class MqttServerControl : UserControl
    {
        private IMqttServer mqttServer;
        public MqttServerControl()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            Size = new Size(880, 450);
        }

        private async void but_Start_Click(object sender, EventArgs e)
        {
            try
            {

                var mqttServerFactory = new MqttFactory();
                var mqttServerOptions = new MqttServerOptionsBuilder()
                                           .WithDefaultEndpoint()
                                           .WithDefaultEndpointBoundIPAddress(System.Net.IPAddress.Parse(txt_Address.Text))
                                           .WithDefaultEndpointPort(int.Parse(txt_Port.Text))
                                           //.WithTcpKeepAliveInterval(50)
                                           //.WithKeepAlive()
                                           .WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(10))
                                           .WithConnectionBacklog(100)
                                           .Build();
                mqttServer = mqttServerFactory.CreateMqttServer();
               
                mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(
                    con =>
                    {
                        WriteLine($"客户端连接：{con.ClientId}");
                        return Task.CompletedTask;

                    });
                mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(
                    con =>
                    {
                        WriteLine($"客户端断开：{con.ClientId}");
                        return Task.CompletedTask;
                    });
                //绑定客户端断开事件

                mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(con =>
                {
                    WriteLine($"服务端停止");
                    return Task.CompletedTask;
                });
                
                mqttServer.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate(
                    d =>
                    {
                        WriteLine($"客户端{d.ClientId}订阅主题：{d.TopicFilter.Topic}");
                        return Task.CompletedTask;
                    }); //客户端订阅主题

                mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(d => {
                    WriteLine($"客户端{d.ClientId}取消订阅主题：{d.TopicFilter}");
                    return Task.CompletedTask;
                });

                mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(
                    d =>
                    {
                        WriteLine($"客户端{d.ClientId}订阅的主题:[{d.ApplicationMessage.Topic}]   发布消息：[{Encoding.UTF8.GetString(d.ApplicationMessage.Payload)}] qos等级:[{d.ApplicationMessage.QualityOfServiceLevel}]");
                        return Task.CompletedTask;
                    });               
                WriteLine($"Mqtt服务启动中");
                await mqttServer.StartAsync(mqttServerOptions);

            }
            catch (Exception ex)
            {
                WriteLine($"err：{ex.Message}");
            }
        }

        private async void but_Stop_Click(object sender, EventArgs e)
        {

            if (mqttServer != null && mqttServer.IsStarted)
                await mqttServer.StopAsync();

        }

        private void WriteLine(string msg = "")
        {
            txt_msg.AppendText($"[{DateTime.Now.ToString()}]{msg} \r\n");
        }
    }
}
